package com.zhkj.txg.module.home.ui

import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Observer
import com.google.android.material.tabs.TabLayout
import com.google.gson.Gson
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.SPUtil
import com.zhkj.txg.R
import com.zhkj.txg.base.GlideApp
import com.zhkj.txg.module.cart.ui.CartFragment
import com.zhkj.txg.module.cart.ui.CartFragmentNew
import com.zhkj.txg.module.find.ui.CategoryFragment
import com.zhkj.txg.module.find.ui.FindFragment
import com.zhkj.txg.module.home.entity.ShopInfo
import com.zhkj.txg.module.home.vm.HomeViewModel
import com.zhkj.txg.module.login.ui.BindMobileActivity
import com.zhkj.txg.module.login.ui.LoginActivity
import com.zhkj.txg.module.mine.ui.MineFragment
import com.zhkj.txg.module.product.popup.UpdatePopupWindow
import com.zhkj.txg.utils.AppUtils
import com.zhkj.txg.utils.ImageUtils
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_cart_new.*
import java.lang.Exception

class MainActivity : ViewModelActivity<HomeViewModel>() {

    companion object {
        val LOGOUT = "logout"
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }

    override val layoutResId: Int = R.layout.activity_main
    override fun setViewModel(): HomeViewModel = createViewModel()

    private val homeFragment: HomeFragment by lazy { HomeFragment() }
    private val categoryFragment: CategoryFragment2 by lazy { CategoryFragment2() }
    private val cartFragment: CartFragmentNew by lazy { CartFragmentNew() }
    private val myFragment: MineFragment by lazy { MineFragment() }

    private var lastBackPressMillis: Long = 0
    private var lastTabPosition = 0
    private var currentTabPosition = -1

    /**
     * 自定义布局的对话框
     */
    private fun layDialog(imgUrl: String) {
        val view: View = LayoutInflater.from(this).inflate(
            R.layout.dialog_novice_welfare, null, false
        )
        val dialog = Dialog(this)
        dialog.setContentView(view)
        dialog.window!!.setBackgroundDrawableResource(android.R.color.transparent)
        val ivNoviceWelfare: ImageView = view.findViewById(R.id.ivNoviceWelfare)
        val tvNotifyClose: TextView = view.findViewById(R.id.tvNotifyClose)
        GlideApp.with(this).load(imgUrl)
            .placeholder(R.drawable.ic_loading).error(R.drawable.ic_loading).into(ivNoviceWelfare)
        // 取消按钮
        tvNotifyClose.setOnClickListener {
            dialog.dismiss()
        }
        dialog.show()
    }

    override fun initUI() {

        val noviceWelfare = SPUtil.getInstance().getString(BindMobileActivity.NOVICE_WELFARE)
        if (!noviceWelfare.isNullOrEmpty()) {
            layDialog(noviceWelfare)
        }
        SPUtil.getInstance().putString(BindMobileActivity.NOVICE_WELFARE, "")


        with(bottomTab) {
            addTab(newTab().setCustomView(R.layout.item_tab_home))
            addTab(newTab().setCustomView(R.layout.item_tab_find))
            addTab(newTab().setCustomView(R.layout.item_tab_cart))
            addTab(newTab().setCustomView(R.layout.item_tab_my))
            addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabReselected(tab: TabLayout.Tab?) = Unit
                override fun onTabUnselected(tab: TabLayout.Tab?) {
                    lastTabPosition = tab?.position ?: 0
                }

                override fun onTabSelected(tab: TabLayout.Tab?) {
                    val targetPosition = tab?.position ?: 0
                    if (targetPosition >= 2 && AccountManager.getToken().isEmpty()) {
                        getTabAt(lastTabPosition)?.select()
                        LoginActivity.jump2Login(this@MainActivity)
                    } else {
                        showFragment(targetPosition)
                        currentTabPosition = targetPosition
                    }
                    if (targetPosition == 2) {
                        val view = tab?.customView
                            ?: return
                        val tvCartBag = view.findViewById<TextView>(R.id.tvCartBag)
                        tvCartBag.visibility = View.GONE
                    } else {
                        getCartNew()
                    }
                }
            })
        }
        showFragment(0)
    }

    private val updatePopupWindow: UpdatePopupWindow by lazy {
        UpdatePopupWindow(this) {
            downLoad(it)
            updatePopupWindow.dismiss()
        }
    }

    /**
     * 下载
     */
    fun downLoad(url: String?) {
        val packageName = "com.android.browser"
        val intent = Intent()
        intent.action = Intent.ACTION_VIEW
        if (AppUtils.isApplicationInstall(this, packageName)) {
            intent.setClassName(packageName, "com.android.browser.BrowserActivity")
        }
        intent.data = Uri.parse(url)
        startActivity(intent)
    }

    override fun initData() {
        viewModel.getConfig()
        viewModel.getVersion()
        getCartNew()
    }

    override fun initViewModel() {
        // 登录信息过期，重新登录
        viewModel.loginStatusSubscribe().observe(this, Observer {
            if (it.tokenInvalid) {
                LoginActivity.jump2Login(this)
            }
        })
        // 切换账号，重新登录客服系统
        viewModel.accountChangeSubscribe().observe(this, Observer {
//            VP53Manager.getInstance().LoginService(AccountManager.getChatId())
        })
        // 退出登录，退出客服系统
        viewModel.logoutSubscribe().observe(this, Observer {
//            VP53Manager.getInstance().QuitChatServer { s: String? -> print(s) }
        })
        // tab页回退
        viewModel.backFragmentSubscribe().observe(this, Observer {
            showFragment(lastTabPosition)
            bottomTab.getTabAt(lastTabPosition)?.select()
        })
        // 跳转的数据观察
        viewModel.tabIndexLiveData.observe(this, Observer {
            bottomTab.getTabAt(it)?.select()
        })
        // 版本更新的数据观察VersionResponse
        viewModel.updateLiveData.observe(this, Observer {
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                it.response?.data?.let {entity ->
                    if (entity.versionCode > AppUtils.getAppVersionCode(this)) {
                        updatePopupWindow.setForce(entity.enforce)
                        updatePopupWindow.setData(entity.downloadUrl)
                        updatePopupWindow.showPopupWindow()
                    }
                }
            }
        })
        // 商品加入购物车观察者
        viewModel.addCartLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                toast(getString(R.string.add_cart_success))
                getCartNew()
            }
        })
        // 购物车商品观察者
        viewModel.cartLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                var number = 0
                response.response?.data?.let {
                    it.cartList.forEach { cart ->
                        cart.goodsList.forEach { goods ->
                            number += goods.goodsNumber
                        }
                    }
                }
                val view = bottomTab.getTabAt(2)?.customView
                    ?: return@Observer
                val tvCartBag = view.findViewById<TextView>(R.id.tvCartBag)
                if (number > 0) {
                    tvCartBag.visibility = View.VISIBLE
                    tvCartBag.text = if (number > 999) "..." else number.toString()
                } else {
                    tvCartBag.visibility = View.GONE
                }
            }
        })
    }

    fun getCartNew() {

        // 获取购物车参数
        val shopInfo1 = SPUtil.getInstance().getString(AccountManager.SHOP_INFO)
        val shopInfo2 = try {
            val gson = Gson()
            gson.fromJson<ShopInfo>(shopInfo1, ShopInfo::class.java)
        } catch (e: Exception) {
            null
        }
        viewModel.getCartNew(hashMapOf("shop_id" to shopInfo2?.id.toString()))
    }

    override fun onBackPressed() {
        if (System.currentTimeMillis() - lastBackPressMillis < 2500) super.onBackPressed()
        else {
            lastBackPressMillis = System.currentTimeMillis()
            toast(getString(R.string.exit_hint))
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        val logout = intent?.getBooleanExtra(LOGOUT, false) ?: false
        if (logout) {
            bottomTab.getTabAt(0)?.select()
            showFragment(0)
        }
    }

    private fun showFragment(index: Int) {
        if (currentTabPosition == index) return
        val fragment = when (index) {
            1 -> categoryFragment
            2 -> cartFragment
            3 -> myFragment
            else -> homeFragment
        }
        hideFragment().apply {
            if (!fragment.isAdded)
                add(R.id.containerMain, fragment)
        }.show(fragment)
            .setMaxLifecycle(fragment, Lifecycle.State.RESUMED)
            .commit()
    }

    private fun hideFragment(): FragmentTransaction {
        return supportFragmentManager.beginTransaction().apply {
            for (fragment in supportFragmentManager.fragments) {
                hide(fragment)
            }
        }
    }
}

class BackTabEvent